package com.meadin.agent.weixin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONObject;

import com.meadin.agent.utils.HttpUtils;

// 生成二维码
public class CreateCode {

	private static final String ACCESS_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxe07edaae488dd45e&secret=357650cf20344e505c78e059129ace99";
	private static final String APP_ID = "wxe07edaae488dd45e";
	private static final String SECRET = "357650cf20344e505c78e059129ace99";
	private static final String CREATE_CODE = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token";
	private static final String ACCESS_TOKEN = "6_yAOi9Xibtg-0kUXsGD440WsNLXmXSHIgFsQbk8ypNHZ5GcEMF0Ht71AMmuzM3G2ra5qDYau8CaaqN7U-T11LdqQEVFJakcQHK1aq7Vo3Dq15rdXuR0tGfO6zSFY73h5wlxhANmz7RE9MlPw6NZNeABAUGU";

	public static void getAccessToken() {
		String result = HttpUtils.sendGet(ACCESS_URL);
		System.out.println(result);
	}

	public static void getCode() throws Exception {
		String url = CREATE_CODE + ACCESS_TOKEN;
		FileOutputStream outputStream = new FileOutputStream(new File("C:\\code\\01.jpg"));
		PrintWriter out = null;
		InputStream in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性 注意Authorization生成
			conn.setRequestProperty("Content-Type", "application/json");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
			JSONObject obj = new JSONObject();
			obj.put("path", "page/weixin/link");
			// 发送请求参数
			out.print(obj);
			// flush输出流的缓冲
			out.flush();
			int byteRead = 0;
			in = conn.getInputStream();
			byte[] bytes = new byte[1024];
			while ((byteRead = in.read(bytes, 0, 1024)) != -1) {
				outputStream.write(bytes, 0, byteRead);
			}

		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
				if (outputStream != null) {
					outputStream.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}

	}

	public static void main(String[] args) throws Exception {
		// getAccessToken();
		getCode();
	}
}
